# Name: JoinBufferGrid.py - MCBS 10/18/2014
# Description: Joins Buffer area to grid.

# import system module
import arcpy
from arcpy import env
#from arcpy.sa import *


# Set workspace environment:
#env.workspace = "CanasatData.gdb"
env.workspace = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\CanasatData.gdb"
env.overwriteOutput = True
#arcpy.CheckOutExtension("Spatial")

# Folder to store tables:
PathForTables = "C:\Users\Marcelo\Documents\Sugarcane\Offline Data\MunicBasedData\Tables"

# Input grid:
GridName      = "G1kmMiR"
# Output grids name:
OutName       = "G1kmMiRBuffer40km"

# fieldmappings   = arcpy.FieldMappings()
# fieldmappings.addTable("CSBuffer40km")
# fieldmappings.addTable(GridName)

arcpy.SpatialJoin_analysis(GridName, "CSBuffer40km", OutName,
	                           "JOIN_ONE_TO_MANY", "KEEP_ALL", "",
							   "COMPLETELY_WITHIN", "", "")
print "Joining attributes from CSBuffer40km to grid."
print "New Grid file containing attributes created: " + OutName
print " "
# Save .dbf tables in specified folder
TableName    = OutName + ".dbf"
arcpy.TableToTable_conversion(OutName, PathForTables, TableName)






